<template>
  <div>
    <div v-loading="pageLoading" class="container" style="padding-bottom: 8px;max-height: auto">
      <div v-if="!showMobilePage" class="relative mb16 filter">
        <FilterInput ref="FilterToolRef" v-model="paramsObj" :filter-list="filterList" show-search-btn @handelClick="queryClick" @queryEmpty="queryEmpty" />
        <createBtn style="margin-right: 10px;" text="添加分类" class="add-btn" @click.native="handleOpenAdd"/>
      </div>
      <ul ref="content" :style="showMoreStatus === 1 ? `max-height: ${textHeight}` : ''" :class="{ 'statusText': showMoreStatus === 1 }" class="type-ul">
        <draggable
          v-model="tagData"
          v-bind="dragOption"
          :move="onMove"
          handle=".type-li"
          filter=".unmove"
          class="tag-box"
          @end="moveChange">
          <transition-group type="transition" class="draggable-li-box">
            <li
              v-for="item in tagData"
              :key="item.id"
              :data-id="item.id"
              :data-name="item.name"
              :class="{'active-type': activeTypeId === item.id, 'unmove': [0, -1, -2, -3].includes(item.id)}"
              class="type-li"
              @click.capture="changeSort(item.id)"
              @drop="handleDrop($event, item)"
            >
              <div v-if="[-2, -3].includes(item.id)" class="flex">
                <span>{{ item.name }}</span>
                <img :src="more" :class="{ 'rotate': item.id === -3 }" class="more-icon">
              </div>
              <template v-else>
                <ToolTip :content="item.name" />
                <el-dropdown v-if="![0, -1, -2, -3].includes(item.id)" class="dropdown-more">
                  <div class="el-dropdown-link" @click.stop="() => {}">
                    <div class="dot-btn">
                      <div class="dot" />
                      <div class="dot" />
                      <div class="dot" />
                    </div>
                  </div>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="handleEditType(item)">编辑</el-dropdown-item>
                    <el-dropdown-item @click.native="handleDelType(item)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </li>
          </transition-group>
        </draggable>
      </ul>
    </div>
    <div v-loading="moduleLoading" class="tag-module-box container">
      <div v-if="activeModule.moduleIds && activeModule.moduleIds.length" :class="{'mb8': !(activeModule.platforms && activeModule.platforms.length)}" class="flex flexwrap">
        <span class="module-label mb8">适用模块：</span>
        <p v-for="(cur, index) in activeModule.module" :key="index" class="module-text mb8">{{ cur }}</p>
      </div>
      <div v-if="activeModule.platforms && activeModule.platforms.length" class="flex mb8 flexwrap">
        <span class="module-label mb8">适用平台：</span>
        <p v-for="(cur, index) in activeModule.platforms" :key="index" class="module-text module-platform">
          <ToolTip :content="cur.name" />
        </p>
      </div>
      <div v-if="!tagsList || !tagsList.length">
        <div v-if="activeTypeId !== 0 && activeTypeId !== -1" class="add-icon" @click="toAddTag">
          <span>+</span>
        </div>
        <EmptyPlaceholder :empty-img-top="'50px'"/>
      </div>
      <div v-else>
        <div v-if="activeTypeId === 0 || activeTypeId === -1" class="tag-list">
          <div v-for="(i, index) in tagsList" :key="index" class="tag-item" style="max-width: 120px;">
            <ToolTip :content="i.name"/>
          </div>
        </div>
        <div v-else class="tag-list">
          <draggable
            v-model="tagsList"
            v-bind="dragOptions"
            handle=".draggable-move"
            class="tag-box"
            @end="draggableChange">
            <transition-group :data-parent-id="activeTypeId" type="transition" class="draggable-item-list">
              <template v-if="tagsList && tagsList.length">
                <div
                  v-for="(i, index) in tagsList"
                  :key="index"
                  :data-id="i.id"
                  :class="{'active-tag-item': (i._isAdd && !i._isEdit) || (i._isEdit && !i._isAdd), 'tag-item-read': !i._isAdd && !i._isEdit}"
                  class="tag-item"
                >
                  <div v-loading="tagLoading" v-if="i._isAdd && !i._isEdit" element-loading-background="#eff3fb" class="tree-main" @click.prevent.stop="() => {}">
                    <el-input v-model="i.name" :maxlength="50" size="small" class="tag-input" placeholder="请输入内容" >
                      <div slot="suffix" class="el-input__icon">
                        <i class="el-icon-check" @click.stop="httpAddSetting(i)" />
                        <img :src="delActive" class="el-icon-error" @click.stop="cancelTag(index)" >
                      </div>
                    </el-input>
                  </div>
                  <div v-loading="tagLoading" v-else-if="i._isEdit && !i._isAdd" element-loading-background="#eff3fb" class="tree-main" @click.prevent.stop="() => {}">
                    <el-input v-model="i.editName" :maxlength="50" size="small" class="tag-input" placeholder="请输入内容" >
                      <div slot="suffix" class="el-input__icon">
                        <i class="el-icon-check" @click.stop="httpEditSetting(i)" />
                        <img :src="delActive" class="el-icon-error" @click.stop="toEditSetting('', i, false)" >
                      </div>
                    </el-input>
                  </div>
                  <template v-else>
                    <div class="label-text draggable-move" @dblclick.stop="toEditSetting(i.name, i, !i._isEdit)">
                      <ToolTip :content="i.name"/>
                    </div>
                    <img :src="del" class="el-icon-error" style="width: 14px;" @click.stop="handleDelTag(i)" >
                  </template>
                </div>
              </template>
            </transition-group>
          </draggable>
          <div v-if="activeTypeId !== 0 && activeTypeId !== -1" class="add-icon" @click="toAddTag">
            <span>+</span>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :append-to-body="false"
      :show-close="false"
      :class="{'mobile-el-dialog': showMobilePage}"
      :close-on-click-modal="false"
      class="small-common-dialog-size create-Income-kind-dialog">
      <Title :title="queryData.id ? '编辑分类' : '添加分类'" font-size="16px" style="margin-bottom:20px;"/>
      <el-form
        ref="sortForm"
        :model="queryData"
        :label-position="showMobilePage?'left':'right'"
        :rules="rules"
        label-width="86px"
        class="setting-form lineHeight32">
        <el-form-item label="分类名称" prop="name" style="margin-bottom: 24px;">
          <el-input
            v-model.trim="queryData.name"
            type="text"
            size="small"
            maxlength="50"
            placeholder="请输入分类名称"
          />
        </el-form-item>
        <el-form-item label="适用模块" prop="moduleIds" style="margin-bottom: 24px;">
          <el-tooltip :open-delay="800" placement="top">
            <div slot="content" style="max-width: 200px;">{{ getModuleNames(queryData.moduleIds) }}</div>
            <el-select
              v-model="queryData.moduleIds"
              multiple
              size="small"
              class="tag-module-select"
              collapse-tags
              style="width: 100%;"
              clearable>
              <el-option
                v-for="item in modules"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-tooltip>
        </el-form-item>
        <el-form-item v-if="showPlatform" label="适用平台" prop="platforms" style="margin-bottom: 24px;">
          <el-select
            v-model="queryData.platforms"
            multiple
            size="small"
            class="tag-module-select"
            collapse-tags
            style="width: 100%;"
            clearable
            @change="selectPlatform">
            <el-option
              v-for="item in orderPlatformOption"
              :key="item.id"
              :label="item.value"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-row :gutter="8" class="response-el-row">
          <el-col :span="12">
            <el-form-item label="文字颜色" prop="color" style="margin-bottom: 15px;">
              <div>
                <el-color-picker
                  slot="suffix"
                  v-model="queryData.color"
                  show-alpha
                  color-format="rgb"
                  size="small"
                  style="margin-right: -5px;"
                  @active-change="selectColor" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="效果预览" style="margin-bottom: 24px;">
              <span :style="{color: curColor || 'rgba(64, 110, 255, 1)', background: curColor ? changeColorAlphaVal(curColor, 0.14) : 'transparent'}" class="tag-result">标签名称</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="flex-center">
        <el-button :loading="submitLoading" type="primary" size="small" @click="handleOk">确定</el-button>
        <el-button class="cancel-btn-style" size="small" style="width: 80px" @click="handleClose">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Title from '@/components/Title';
import createBtn from '@/components/Common/baseComponent/createBtn';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import { TAG_MODULES } from '@/utils/const';
import { paramsAryToStr } from '@/utils/paramsFormat';
import { platformList } from '@/api/select';
import { queryTagReference, getTagList, editSetting, addSetting, deleteSetting } from '@/api/setting';
import ElMessage, { showModal } from '@/utils/message';
import del from '@/assets/setting/del.png';
import delActive from '@/assets/setting/del-active.png';
import more from '@/assets/setting/more.png';
import { mapState } from 'vuex';
import draggable from 'vuedraggable';
import { changeColorAlphaVal } from '@/utils/tools';

export default {
  components: { Title, createBtn, draggable, EmptyPlaceholder },
  data() {
    return {
      del,
      delActive,
      more,
      activeTypeId: 0,
      tagData: [],
      paramsObj: {},
      dialogVisible: false,
      queryData: {
        name: '',
        moduleIds: [],
        platforms: [],
        color: 'rgba(64, 110, 255, 1)'
      },
      submitLoading: false,
      orderPlatformOption: [],
      rules: {
        'name': [{ required: true, message: '请输入名称', trigger: 'blur' }],
        'moduleIds': [{ required: true, message: '请选择适用模块', trigger: 'change' }],
        'platforms': [{ required: true, message: '请选择适用平台', trigger: 'change' }]
      },
      tagsList: [],
      tipMessage: null,
      pageLoading: false,
      tagLoading: false,
      isInit: true,
      onEditTag: false, // 存在正在编辑的标签
      moveTypeId: 0,
      moduleLoading: false,
      allPlatform: [], // 所有平台id
      clearAll: false, // 筛选项"全选"是否被选择
      selectAll: false, // 弹窗适用平台"全选"是否被选择
      textHeight: null, // 框中内容的高度
      moreIndex: 0,
      showMoreStatus: 0, // 0-无状态，1-展开，2-收起
      curColor: 'rgba(64, 110, 255, 1)'
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    filterList() {
      const arr = [
        { keyword: 'name', name: '标签名称', labelWidth: '68px', type: 'input' },
        { keyword: 'moduleIds', name: '适用模块', type: 'mulSelect', options: this.modules, labelName: 'name', valueName: 'id' },
        { keyword: 'platforms', name: '适用平台', type: 'mulSelect', options: this.orderPlatformOption, labelName: 'value', valueName: 'id' }
      ];
      return arr;
    },
    arrayKeyArr() {
      return ['moduleIds', 'platforms'];
    },
    dragOption() {
      return {
        animation: 200,
        group: 'a',
        disabled: false,
        ghostClass: 'ghost'
      };
    },
    dragOptions() {
      return {
        animation: 200,
        group: 'description',
        disabled: false,
        ghostClass: 'ghost'
      };
    },
    modules() {
      return [
        { id: TAG_MODULES.GLOBAL, name: '全局通用' },
        // { id: TAG_MODULES.CHANNEL, name: '渠道订单' },
        { id: TAG_MODULES.PROJECT, name: '项目订单' },
        // { id: TAG_MODULES.PROJECT_CHANNEL, name: '项目渠道单' },
        { id: TAG_MODULES.IMAGE_AUTH, name: '商务订单' },
        // { id: TAG_MODULES.MARKET_AUTH, name: '营销授权' },
        { id: TAG_MODULES.RESOURCE, name: '账号资源' },
        { id: TAG_MODULES.SETTLE_CUSTOMER, name: '销售客户' },
        { id: TAG_MODULES.MENGLI_CUSTOMER, name: '萌力客户' },
        { id: TAG_MODULES.SETTLE_SUPPLIER, name: '飞博供应商' },
        { id: TAG_MODULES.COMMERCE_SUPPLIER, name: '有赞供应商' },
        { id: TAG_MODULES.MENGLI_SUPPLIER, name: '萌力供应商' },
        { id: TAG_MODULES.PROCESS, name: '审批流程' },
        { id: TAG_MODULES.FILTER, name: '达人初筛' },
        { id: TAG_MODULES.SIGN_UP, name: '签约内审' },
        { id: TAG_MODULES.FLY_NOTICE, name: '飞来询单' }
        // { id: TAG_MODULES.MINI_PROGRAM, name: '飞来通告小程序' }
      ];
    },
    showPlatform() {
      if (!this.queryData.moduleIds || this.queryData.moduleIds.length === 0) {
        return false;
      }
      const res = this.queryData.moduleIds.some(item => {
        return [TAG_MODULES.GLOBAL, TAG_MODULES.RESOURCE, TAG_MODULES.FILTER, TAG_MODULES.SIGN_UP].includes(item);
      });
      return res;
    },
    activeModule() {
      const arr = this.tagData.filter(item => {
        return item.id === this.activeTypeId;
      });
      return arr[0] || {};
    }
  },
  watch: {
    'paramsObj.platforms': {
      handler(newVal, oldVal) {
        const newV = newVal || [];
        const oldV = oldVal || [];
        // new有全选，old没有全选，此时需要把所有选项勾上
        if (newV.includes(-1) && !oldV.includes(-1)) {
          this.$set(this.paramsObj, 'platforms', this.allPlatform);
        }
        // new没有全选，old有全选，此时需要把所有选项清空
        if (!newV.includes(-1) && oldV.includes(-1)) {
          // old.length等于全部选项的length，说明此时是取消全选
          // 加一个clearAll标志，表示"全选"选项是否被勾选上
          if (oldV.length === this.allPlatform.length) {
            this.clearAll = false;
          }
          if (!this.clearAll) {
            this.$set(this.paramsObj, 'platforms', []);
          }
        }
        // new有全选，old有全选，但是new.len < old.len，此时是取消某个选项，需要把-1去掉
        if (newV.includes(-1) && oldV.includes(-1) && newV.length < oldV.length) {
          const temp = newV.filter(item => item !== -1);
          this.clearAll = true;
          this.$set(this.paramsObj, 'platforms', temp);
        }
        // newV没有全选，但是newV.len为全部选项，此时需要勾上"全部"选项
        if (!newV.includes(-1) && !oldV.includes(-1) && newV.length === this.allPlatform.length - 1) {
          newV.push(-1);
          this.$set(this.paramsObj, 'platforms', newV);
        }
      }
    }
  },
  created() {
    this.getTag();
    this.platformList();
  },
  methods: {
    changeColorAlphaVal,
    getModuleNames(list) {
      if (!Array.isArray(list) || !list.length) return '请选择';
      const result = [];
      list.forEach(id => {
        const currModule = this.modules.filter(item => item.id === id);
        if (Array.isArray(currModule) && currModule.length) {
          result.push(currModule[0].name);
        }
      });
      return result;
    },
    getMoreIndex() {
      // 计算展开更多内容超出显示
      setTimeout(() => {
        // lineHeight：每行高度*保留几行
        const lineHeight = 48 * 2;
        this.textHeight = `${lineHeight}px`;
        if (this.$refs.content.offsetHeight > lineHeight) {
          this.showMoreStatus = 1;
          // 计算展开应该放在第几个位置
          const width = this.$refs.content.offsetWidth;
          // 计算一行能放几个
          const n = (width - (width % 140)) / 140;
          this.moreIndex = n * 2 - 1;
          this.tagData.splice(this.moreIndex, 0, { id: -2, name: '展开' });
        }
      }, 200);
    },
    async platformList() {
      try {
        const result = await platformList();
        this.orderPlatformOption = result.data;
        this.orderPlatformOption.unshift({ id: -1, value: '全选' });
        this.allPlatform = result.data.map(item => item.id);
      } catch (error) {
        console.log(error);
      }
    },
    async getTag() {
      try {
        const params = JSON.parse(JSON.stringify(this.paramsObj));
        paramsAryToStr(this.arrayKeyArr, params);
        if (!this.isInit) {
          params.typeId = this.activeTypeId;
        }
        this.moduleLoading = true;
        const result = await getTagList(params);
        if (result.code === 200) {
          result.data.forEach(item => {
            item.module = this.getModuleNames(item.moduleIds);
          });
          if (this.isInit && result.data.length) {
            this.activeTypeId = result.data[0].id;
            this.isInit = false;
          }
          this.tagData = result.data;
          for (let i = 0; i < this.tagData.length; i++) {
            if (this.tagData[i].id === this.activeTypeId) {
              this.tagsList = this.tagData[i].item || [];
              break;
            }
          }
          if (result.data.length === 0) {
            this.tagsList = [];
          }
          if (this.showMoreStatus === 0) {
            this.getMoreIndex();
          } else if (this.showMoreStatus === 1) {
            this.tagData.splice(this.moreIndex, 0, { id: -2, name: '展开' });
          } else if (this.showMoreStatus === 2) {
            this.tagData.push({ id: -3, name: '收起' });
          }
        }
        this.moduleLoading = false;
      } catch (error) {
        this.moduleLoading = false;
        console.log(error);
      }
    },
    changeSort(val) {
      if (val === -2) {
        this.showMoreStatus = 2;
        this.tagData.splice(this.moreIndex, 1);
        this.tagData.push({ id: -3, name: '收起' });
      } else if (val === -3) {
        this.showMoreStatus = 1;
        const len = this.tagData.length - 1;
        this.tagData.splice(len, 1);
        this.tagData.splice(this.moreIndex, 0, { id: -2, name: '展开' });
      } else {
        this.activeTypeId = val;
        this.onEditTag = false;
        this.getTag();
      }
    },
    queryClick() {
      this.isInit = true;
      this.showMoreStatus = 0;
      this.getTag();
    },
    queryEmpty() {
      this.paramsObj = {};
      this.getTag();
    },
    handleOpenAdd() {
      this.curColor = 'rgba(64, 110, 255, 1)';
      this.queryData.color = this.curColor;
      this.dialogVisible = true;
    },
    handleOk() {
      this.$refs.sortForm.validate((valid) => {
        if (valid) {
          const method = this.queryData.id ? editSetting : addSetting;
          const params = this.queryData;
          params.type = 15;
          if (!this.showPlatform) {
            params.platforms = [];
          }
          if (params.platforms.includes(-1)) {
            const temp = params.platforms.filter(item => item !== -1);
            params.platforms = temp;
          }
          method(params).then(res => {
            if (res.code === 200) {
              // 成功
              this.handleClose();
              this.getTag();
              ElMessage.success('操作成功');
            }
          });
        }
      });
    },
    handleClose() {
      this.queryData = {};
      this.$refs['sortForm'] && this.$refs['sortForm'].resetFields();
      this.dialogVisible = false;
      this.selectAll = false;
      this.curColor = '';
    },
    handleEditType(item) {
      this.queryData = JSON.parse(JSON.stringify(item));
      if (this.queryData.platforms) {
        this.queryData.platforms = this.queryData.platforms.map(item => item.id);
        if (this.queryData.platforms.length === this.allPlatform.length - 1) {
          this.queryData.platforms.push(-1);
          this.selectAll = true;
        }
      }
      this.curColor = item.color || 'rgba(64, 110, 255, 1)';
      this.dialogVisible = true;
      this.$refs['sortForm'] && this.$refs['sortForm'].clearValidate();
    },
    handleDelType(item) {
      queryTagReference(item.id).then(res => {
        const isReference = res.data && res.data.result || false;
        const tipText = isReference ? '该标签分类下存在被引用标签，是否确定删除？' : '是否确定删除？';
        showModal(tipText).then(_ => {
          const params = { id: item.id, name: item.name, type: 15 };
          deleteSetting(params).then(_ => {
            this.isInit = true;
            this.getTag();
            this.$message.success('删除成功');
          }).finally(_ => {
            this.showMoreStatus = 0;
          });
        });
      });
    },
    draggableChange(customEventDom) {
      const timer = setTimeout(() => {
        const { newIndex, oldIndex, newDraggableIndex, oldDraggableIndex } = customEventDom;
        const fromParentId = customEventDom.from.dataset.parentId;
        const toParentId = customEventDom.to.dataset.parentId;
        if (newIndex === oldIndex && newDraggableIndex === oldDraggableIndex && fromParentId === toParentId && !this.moveTypeId) {
          return;
        }
        const params = {};
        params.moveToIndex = newIndex; // 拖拽后标签排序
        const currHandleTag = customEventDom.to.children[newIndex]; // 拖拽的标签
        params.name = currHandleTag.innerText; // 拖拽的标签名称
        params.id = currHandleTag.dataset.id; // 拖拽的标签id
        params.orderPlatformId = customEventDom.to.dataset.parentId; // 拖拽至目标位置的一级标签id
        if (this.moveTypeId) { // 跨分类拖动
          params.moveToIndex = 0;
          params.orderPlatformId = this.moveTypeId;
        }
        this.orderCallback(params, true);
        clearTimeout(timer);
      }, 17);
    },
    orderCallback(params, needTip = false) {
      params.type = 15;
      if (this.moveTypeId && needTip) {
        queryTagReference(params.id).then(res => {
          const isReference = res.data && res.data.result || false;
          const tipText = isReference ? '该标签已被引用，移动分类后适用模块可能发生变化，请确认是否移动？' : '是否确定移动分类？';
          showModal(tipText, '', {}, true).then(_ => {
            this.pageLoading = true;
            editSetting(params).then(res => {
              this.pageLoading = false;
              if (res.code !== 200 || this.moveTypeId) {
                this.getTag();
              } else {
                this.tipMessage && this.tipMessage.close();
                this.tipMessage = this.$message.success('操作成功');
              }
              this.moveTypeId = 0;
            }).catch(_ => {
              this.pageLoading = false;
              this.moveTypeId = 0;
              this.getTag();
            });
          }).catch(_ => {
            this.getTag();
          });
        });
      } else {
        this.pageLoading = true;
        editSetting(params).then(res => {
          this.pageLoading = false;
          if (res.code !== 200 || this.moveTypeId) {
            this.getTag();
          } else {
            this.tipMessage && this.tipMessage.close();
            this.tipMessage = this.$message.success('操作成功');
          }
          this.moveTypeId = 0;
        }).catch(_ => {
          this.pageLoading = false;
          this.moveTypeId = 0;
          this.getTag();
        });
      }
    },
    httpAddSetting(data) {
      if (!data.name) {
        ElMessage.warning('请输入内容');
        return;
      }
      const params = {
        type: 15,
        name: data.name,
        orderPlatformId: this.activeTypeId
      };
      this.tagLoading = true;
      addSetting(params).then(res => {
        this.tagLoading = false;
        if (res.code === 200) {
          this.onEditTag = false;
          this.getTag();
          ElMessage.success('新增成功');
        } else {
          ElMessage.success(res.message);
        }
      }).catch(err => {
        this.tagLoading = false;
        console.log(err);
      });
    },
    cancelTag(index) {
      this.tagsList.splice(index, 1);
      this.onEditTag = false;
    },
    httpEditSetting(data) {
      if (!data.editName) {
        ElMessage.warning('请输入内容');
        return;
      }
      const params = {
        type: 15,
        id: data.id,
        name: data.editName || data.name,
        orderPlatformId: this.activeTypeId
      };
      this.tagLoading = true;
      editSetting(params).then(res => {
        this.tagLoading = false;
        if (res.code === 200) {
          this.onEditTag = false;
          this.getTag();
          ElMessage.success('修改成功');
        } else {
          ElMessage.success(res.message);
        }
      }).catch(err => {
        this.tagLoading = false;
        console.log(err);
      });
    },
    toEditSetting(name, data, type) {
      if (name && this.onEditTag) {
        this.$message.warning('存在正在编辑的标签');
        return;
      }
      this.onEditTag = true;
      if (name !== '') {
        this.$set(data, 'editName', name);
      }
      this.$set(data, '_isEdit', type);
      if (!name) {
        this.onEditTag = false;
      }
    },
    handleDelTag(data) {
      queryTagReference(data.id).then(res => {
        const isReference = res.data && res.data.result || false;
        const tipText = isReference ? '该标签已被引用，是否确定删除？' : '是否确定删除？';
        showModal(tipText).then(_ => {
          const params = {
            type: 15,
            id: data.id,
            name: data.name,
            orderPlatformId: this.activeTypeId
          };
          deleteSetting(params).then(res => {
            if (res.code === 200) {
              this.getTag();
              ElMessage.success('删除成功');
            } else {
              ElMessage.error(res.message);
            }
          }).catch(err => {
            console.error(err);
          });
        }).catch(_ => null);
      });
    },
    toAddTag() {
      if (this.onEditTag) {
        this.$message.warning('存在正在编辑的标签');
        return;
      }
      this.onEditTag = true;
      const newChild = { name: '', _isAdd: true };
      this.tagsList.push(newChild);
    },
    onMove(customEventDom) {
      const index = customEventDom.relatedContext.index;
      const len = this.tagData.length - 1;
      if (([0, 1].includes(index)) || (this.showMoreStatus && [this.moreIndex, len].includes(index))) {
        return false;
      }
    },
    moveChange(customEventDom) {
      const timer = setTimeout(() => {
        const params = { type: 15 };
        const { newIndex } = customEventDom;
        params.moveToIndex = newIndex - 1; // 拖拽后标签排序
        const currHandleTag = customEventDom.to.children[newIndex]; // 拖拽的标签
        const temp = this.tagData.filter(item => item.id === Number(currHandleTag.dataset.id));
        if (temp[0].platforms && temp[0].platforms.length) {
          params.platforms = temp[0].platforms.map(item => item.id);
        }
        params.name = currHandleTag.dataset.name; // 拖拽的标签名称
        params.id = currHandleTag.dataset.id; // 拖拽的标签id
        this.orderCallback(params);
        clearTimeout(timer);
      }, 17);
    },
    handleDrop(event, item) {
      if (item.id !== 0 && item.id !== -1) {
        this.moveTypeId = item.id;
      }
    },
    selectPlatform(val) {
      if (val.includes(-1)) {
        // val有-1，selectAll为false，此时是全选，需要把所有选项勾上
        if (!this.selectAll) {
          this.$set(this.queryData, 'platforms', this.allPlatform);
          this.selectAll = true;
        } else if (val.length < this.allPlatform.length) {
          // val有-1，val.len < allPlarform.len，此时是取消某个选项，需要把全选去掉
          const temp = val.filter(item => item !== -1);
          this.$set(this.queryData, 'platforms', temp);
          this.selectAll = false;
        }
      }
      // val没有-1，但val.len为allPlatorm.len
      if (!val.includes(-1) && val.length === this.allPlatform.length - 1) {
        // selectAll为true，此时是取消全选
        if (this.selectAll) {
          this.$set(this.queryData, 'platforms', []);
          this.selectAll = false;
        } else if (!this.selectAll) {
          // selectAll不为true，此时是加上全选
          this.$set(this.queryData, 'platforms', this.allPlatform);
          this.selectAll = true;
        }
      }
    },
    selectColor(val) {
      this.curColor = val;
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 4px;
}
p {
  padding: 0;
  margin: 0;
}
.filter {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  position: relative;
}
.type-ul {
  list-style: none;
  padding: 0;
  margin: 0;
}
.draggable-li-box {
  display: flex;
  flex-wrap: wrap;
  .type-li {
    width: 132px;
    height: 40px;
    padding: 0 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #edeef2;
    border-radius: 4px;
    margin: 0 8px 8px 0;
    font-size: 16px;
    font-weight: bold;
    color: #333;
    position: relative;
    cursor: auto;
    &:hover {
      cursor: move;
    }
    .dropdown-more {
      display: none;
      position: absolute;
      right: 0;
      top: 0;
    }
    .dot-btn {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 32px;
      height: 20px;
      border-radius: 4px;
      .dot {
        width: 4px;
        height: 4px;
        background: #AFB6C8;
        border-radius: 50%;
        margin-right: 3px;
      }
      .dot:last-child {
        margin: 0;
      }
    }
  }
  .unmove:hover {
    cursor: auto;
  }
  .active-type {
    background: #406eff;
    color: #fff;
  }
  .type-li:hover {
    .dropdown-more {
      display: block;
    }
  }
}
.tag-module-box {
  margin-top: 8px;
  height: calc(100vh - 308px);
  .mb8 {
    margin-bottom: 8px;
  }
  .mb16 {
    margin-bottom: 16px;
  }
  .module-label {
    font-size: 12px;
    color: #999;
  }
  .module-text {
    padding: 2px 10px;
    margin-right: 8px;
    border-radius: 10px;
    background-color: #EBEEFD;
    color: #406EFF;
    font-size: 12px;
  }
  .flexwrap {
    flex-wrap: wrap;
  }
  .module-platform {
    max-width: 100px;
    margin-bottom: 8px;
    &:nth-child(3n+2) {
      background-color: #FFF2EB;
      color: #FD8546;
    }
    &:nth-child(3n+3) {
      background-color: #FFE8EA;
      color: #FF4E5F;
    }
    &:nth-child(3n+1) {
      background-color: #E2F8F2;
      color: #31CC9C;
    }
  }
}
.tag-list {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  .draggable-item-list {
    display: flex;
    flex-wrap: wrap;
  }
  .tag-item {
    display: flex;
    align-items: center;
    padding: 0 8px;
    height: 32px;
    border-radius: 4px;
    margin-right: 8px;
    cursor: auto;
    margin-bottom: 8px;
    position: relative;
    background: #fff;
    border: 0.5px solid #ddd;
    .label-text {
      color: #333;
      font-size: 12px;
      max-width: 200px;
      user-select: none;
      cursor: move;
    }
    .icon {
      font-size: 13px;
      color: #999999;
      cursor: pointer;
      margin-left: 3px;
    }
  }
  .tag-item-read {
    .el-icon-error {
      width: 14px;
      cursor: pointer;
      position: absolute;
      top: -6px;
      right: -6px;
    }
  }
  .active-tag-item {
    border: 1px solid #406eff;
    background-color: #fff;
    box-shadow: 0px 3px 6px 0px #ddd;
  }
}
.tag-input {
  display: flex;
  align-items: center;
  background-color: #fff;
  &::v-deep {
    .el-input__inner {
      background-color: #fff;
      font-size: 14px;
      padding: 0 !important;
      border: none;
      height: 100%;
      margin-right: 20px !important;
    }
    .el-input__icon {
      cursor: pointer;
      margin-right: -12px;
    }
    .el-icon-check {
      color: #406eff;
    }
    .el-input__suffix {
      display: flex;
      align-items: center;
      font-size: 14px;
    }
    .el-icon-error {
      width: 14px;
      position: absolute;
      top: -12px;
      right: -20px;
    }
  }
}
.tag-module-select {
  min-width: 150px;
  ::v-deep .el-tag > span {
    max-width: 80px;
  }
  &::v-deep {
    .el-tag.el-tag--info {
      color: #406EFF !important;
      background-color: #EFF3FB !important;
    }
  }
}
.flex-center {
  display: flex;
  justify-content: center;
}
.add-icon {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  border: 0.5px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  span {
    display: inline-block;
    width: 24px;
    height: 24px;
    line-height: 20px;
    background: #f3f5fa;
    border-radius: 4px;
    text-align: center;
    font-size: 24px;
    font-weight: bold;
    color: #406EFF;
  }
}
.statusText {
  overflow: hidden;
  max-height: auto;
}
.more-icon {
  width: 15px;
  height: 8px;
  margin-left: 4px;
}
.rotate {
  transform: rotate(180deg);
}
.tag-result {
  font-size: 12px;
  padding: 2px 10px;
  border-radius: 10px;
}
</style>
